package com.jiancong.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jiancong.config.OssConfig;
import com.jiancong.domain.ResponseResult;
import com.jiancong.enums.AppHttpCodeEnum;
import com.jiancong.exception.SystemException;
import com.jiancong.service.UploadService;
import com.jiancong.utils.PathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import static com.jiancong.enums.AppHttpCodeEnum.*;

@Service
public class UploadServiceImpl implements UploadService {

    @Override
    @Transactional
    public ResponseResult uploadImg(MultipartFile img) {
        OSS ossClient = new OSSClientBuilder().build(OssConfig.getEndpoint(),OssConfig.getAccessKeyId(),OssConfig.getAccessKeySecret());
        //判断文件类型
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名进行判断

        if (!originalFilename.endsWith(".png")) {
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        //如果判断通过上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        // 3. 上传至阿里OSS
        try {
            ossClient.putObject(OssConfig.getBucket(), filePath, new ByteArrayInputStream(img.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(Upload_CANNOT);
        }

        return ResponseResult.okResult("https://ac-blog.oss-cn-guangzhou.aliyuncs.com/" + filePath);
    }
}
